import { useRequestPowerAfterInit } from '@/hooks/useRequestPowerAfterInit';
import type { ProvinceType, StationType } from '@/hooks/useRequestPowerAfterInit';
import { TjFilter, TjHeader } from '@/tjComponents';
import { useSetState } from 'ahooks';
import { useForm } from 'antd/lib/form/Form';
import React, { useState, useEffect, useRef } from 'react';
import { connect } from 'umi';
import TjTable from '../components/TjTable';
import { Button, DatePicker, Select } from 'antd';
import _ from 'lodash';
import TjMarketingUnit from '@/tjComponents/TjMarketingUnit';
import { exportExcel, getOptionalDate, settlementDatas, useNewService } from './services';
import { HttpCode } from '#/utils/contacts.js';
import moment from 'moment';
import { columns, buildTableData, downFile, buildBatchExportData } from './helper';
import classnames from 'classnames';
import { features, useTablePipeline } from 'ali-react-table';
import { SERVER_URL_OBJ } from '../../../../config/urlConfig';
import { downloadFileForFront } from '@/tjComponents/TjUpload/TjUploadContent';
import PreviewContent from './components/PreviewContent';
import './index.less';

const SettlementManage: React.FC<ISettlementManageProps> = (props) => {
  const { CLIENT_ENV } = process.env;
  const [form] = useForm();
  const { initLoading, province, treeData, initResult } = useRequestPowerAfterInit(
    `/power/dataPower/common/${props.menuCode}/t_station`,
    (parmas) => {
      const stationIds = parmas.stations.map((v: StationType) => {
        return v.stationId;
      });
      const obj = {
        stationIds,
        marketId: parmas.value,
        provinceId: parmas.provinceId,
      };
      setCurrentProvinceInfo(parmas);
      getEndDate(obj, true);
      form.setFieldsValue({
        marketId: parmas.value,
        stationIds,
      });
    },
    {
      convertResult: '2',
      matchFirst: 0,
    },
  );
  const [loading, setLoading] = useState<boolean>(true);
  const [dateLoding, setDateLoding] = useState<boolean>(false);
  const [req, setReq] = useSetState<any>({
    marketId: '',
  });
  const [currentProvinceInfo, setCurrentProvinceInfo] = useState<ProvinceType>();
  const [defaultReq, setDefaultReq] = useState<any>();
  const [endDate, setEndData] = useState<moment.Moment>();
  const [tabs, setTabs] = useState<any[]>([]);
  const [activeKey, setActiveKey] = useState<string>('');
  const [dataSourceObj, setDataSourceObj] = useState<Record<string, any[]>>({});
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [selectArr, setSelectArr] = useState<any[]>([]);
  const allData = useRef<Record<string, any>>();
  const [currentPreviewFileName, setCurrentPreviewFileName] = useState<string>('');
  const [currentPreviewFilePath, setCurrentPreviewFilePath] = useState<string>('');

  const changeMarketId = (val: string) => {
    const item = _.find(province, (n: ProvinceType) => n.value === val);
    if (item) {
      setCurrentProvinceInfo(item);
      const stationIds = item.stations.map((v: StationType) => {
        return v.stationId;
      });
      form.setFieldsValue({
        stationIds,
      });
      const obj = {
        stationIds,
        marketId: val,
        provinceId: item.provinceId,
      };
      getEndDate(obj);
    }
  };

  const changeStationIds = (arr: any) => {
    const obj = {
      ...req,
      stationIds: arr,
    };
    getEndDate(obj);
  };

  const getEndDate = (params: any, isInit?: boolean) => {
    setDateLoding(true);
    getOptionalDate(params)
      .then((res: any) => {
        if (res.statusCode === HttpCode.SUCCESS) {
          let startDate = undefined;
          const endDate = res.data ? moment(res.data) : moment();
          if (moment().diff(moment().startOf('month'), 'days') > 1) {
            startDate = moment().startOf('month');
          } else {
            startDate = moment().subtract(1, 'months').startOf('month');
          }
          startDate = endDate < startDate ? endDate : startDate;
          if (isInit) {
            const newParmas = { ...params, date: [startDate, endDate] };
            setReq(newParmas);
            setDefaultReq(newParmas);
          } else {
            form.setFieldsValue({ date: [startDate, endDate] });
          }
          setEndData(endDate);
        }
      })
      .finally(() => setDateLoding(false));
  };

  const query = () => {
    const newParams: any = {
      ...req,
    };

    setLoading(true);
    setSelectArr([]);
    if (newParams.date) {
      newParams.startDate = moment(newParams.date[0]).format('YYYY-MM-DD');
      newParams.endDate = moment(newParams.date[1]).format('YYYY-MM-DD');
      delete newParams.date;
    }
    settlementDatas(newParams)
      .then((res: any) => {
        if (res.statusCode === HttpCode.SUCCESS) {
          let data = _.get(res, 'dataList', null);
          if (useNewService.includes(newParams.marketId)) {
            data = _.get(res, 'data', null);
          }
          if (!data || Object.keys(data).length === 0) {
            setTabs([]);
            setActiveKey('');
            setDataSourceObj({});
            setDataSource([]);
            allData.current = data;
          } else {
            const { tabs, tableData } = buildTableData(data, initResult);
            setTabs(tabs);
            setActiveKey(tabs[0].value);
            setDataSourceObj(tableData);
            setDataSource([...tableData[tabs[0].value]]);
            allData.current = data;
          }
          setCurrentPreviewFileName('');
          setCurrentPreviewFilePath('');
        }
      })
      .finally(() => setLoading(false));
  };

  const onSearch = (value: any) => {
    setReq(value);
  };

  const onReset = (value: any) => {
    const item = _.find(province, (n: ProvinceType) => n.value === value.marketId);
    if (item) {
      setCurrentProvinceInfo(item);
    }
    setReq(value);
  };

  const changeCheckbox = (val: boolean, index: number) => {
    const newDataSource = [...dataSource];
    newDataSource[index].checked = val;
    setDataSource(newDataSource);
  };

  const exportFile = (row: any) => {
    if (row && row.attachmentPath) {
      const env = !CLIENT_ENV || CLIENT_ENV === 'dev' ? 'release' : CLIENT_ENV;
      // @ts-ignore
      const url = `${SERVER_URL_OBJ[env]}/annex/annex/downLoadFile/${row.attachmentPath}`;
      downFile(url, row.attachmentName);
    }
  };

  const batchExport = () => {
    if (allData.current && allData.current[activeKey] && dataSource.length > 0) {
      const obj: any = allData.current[activeKey];
      const dataList = buildBatchExportData(dataSource, obj);
      const params = {
        exportType: 'settlementManage',
        marketId: req.marketId,
        jsonParam: JSON.stringify({
          dataList: dataList,
          marketId: req.marketId,
          startDate: moment(req.date[0]).format('YYYY-MM-DD'),
          endDate: moment(req.date[1]).format('YYYY-MM-DD'),
          attachmentType: activeKey,
          region: req.marketId,
        }),
      };
      exportExcel(params).then((res: any) => {
        const realFileName = res.response.headers.get('content-disposition').split('filename=')[1];
        downloadFileForFront(res.data, decodeURI(realFileName));
      });
    }
  };

  const view = (row: any) => {
    setCurrentPreviewFilePath(row.attachmentPath);
    setCurrentPreviewFileName(row.attachmentName);
  };

  useEffect(() => {
    if (req.marketId) {
      query();
    }
  }, [req]);

  const pipeline = useTablePipeline()
    .input({
      dataSource: dataSource,
      columns: columns({ view, exportFile, changeCheckbox }),
    })
    .use(features.autoRowSpan());

  return (
    <div className="settlement-manage">
      <TjHeader
        left={
          <TjFilter
            onSearch={onSearch}
            onReset={onReset}
            form={form}
            defaultValues={defaultReq}
            loading={initLoading || loading || dateLoding}
            items={[
              {
                name: 'marketId',
                render: (
                  <Select
                    options={province}
                    style={{ width: 180 }}
                    loading={initLoading}
                    onChange={changeMarketId}
                    allowClear={false}
                    showSearch // 开启搜索
                    filterOption={(input, option: any) =>
                      (option.label ?? '').toLowerCase().includes(input.toLowerCase())
                    }
                  />
                ),
              },
              {
                name: 'stationIds',
                render: (
                  <TjMarketingUnit
                    treeData={treeData}
                    marketId={currentProvinceInfo?.value}
                    onChange={changeStationIds}
                  />
                ),
              },
              {
                name: 'date',
                render: (
                  <DatePicker.RangePicker
                    style={{ width: 260 }}
                    placeholder={['开始日期', '结束日期']}
                    format={'YYYYMMDD'}
                    separator="-"
                    disabled={dateLoding}
                    allowClear={false}
                    disabledDate={(current) => {
                      if (endDate) {
                        return current && current > endDate;
                      }
                      return false;
                    }}
                  />
                ),
              },
            ]}
          />
        }
      />

      <div className="settlement-manage-content">
        <div className="settlement-opts">
          <div className="tabs">
            {tabs.length > 0 &&
              tabs.map((v) => {
                return (
                  <div
                    key={v.value}
                    className={classnames('tab', { active: v.value === activeKey })}
                    onClick={() => {
                      setSelectArr([]);
                      setActiveKey(v.value);
                      setDataSource(dataSourceObj[v.value]);
                    }}
                  >
                    {v.label}
                  </div>
                );
              })}
          </div>
          <Button onClick={batchExport}>批量导出</Button>
        </div>

        <div className="mains">
          <div className="left">
            <div className="table-box">
              <TjTable {...pipeline.getProps()} isLoading={loading} />
            </div>
          </div>

          <div className="right">
            <PreviewContent name={currentPreviewFileName} path={currentPreviewFilePath} />
          </div>
        </div>
      </div>
    </div>
  );
};

interface ISettlementManageProps {
  menuCode: string;
}

export default connect(({ global }: any) => ({
  menuCode: global.configure.menuCode,
}))(SettlementManage);
